import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_wallpaper_manager/flutter_wallpaper_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:share_plus/share_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'ads/consent_manager.dart';
import 'ads/ads_unit_id.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'common/loading_spinner.dart'; // 导入公共组件
import 'package:cached_network_image/cached_network_image.dart'; //网络图片缓存到本地
import 'package:http/http.dart' as http;
class DetailPage extends StatefulWidget {
  // final String photourl;
  // final int gif;
  final int imgId;
  final int gif;
  const DetailPage({
    super.key,
    required this.imgId,
    required this.gif,
  });

  @override
  State<DetailPage> createState() => _MyTextPageState();
}

class _MyTextPageState extends State<DetailPage> {
  final _consentManager = ConsentManager.instance;
  RewardedAd? _rewardedAd;
  var _showWatchVideoButton = false;

  InterstitialAd? _interstitialAd;

  // final ScrollController _scrollController = ScrollController();
  late String photourl = '';
  int gif = 0;
  int imgId = 0;
  String imgurl = '';

  bool isMember = false;

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  Future<void> _logScreenView(imgId) async {
    // print('imgId:$imgId');
    await analytics.logScreenView(
      screenName: 'detail Page ES',
      screenClass: 'DetailPage_ES$imgId',
    );
    // setMessage('setCurrentScreen succeeded');
  }

  @override
  void initState() {
    super.initState();
    
    // photourl = widget.photourl;
    gif = widget.gif;
    imgId = widget.imgId;
    loadInsertAd();
    _loadRewardAd();
    _logScreenView(imgId);
    imgurl = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images/$imgId.${gif==0?'webp':'gif'}';
  }


  @override
  void dispose() {
    _interstitialAd?.dispose();
    _rewardedAd?.dispose();
    super.dispose();
  }

  Future<void> setWallpaperImage(String url, int location) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    ByteData byteData = await rootBundle.load(url);
    List<int> imageData = byteData.buffer.asUint8List();
    String externalImagePath = '$tempPath/wallpaper.webp';
    File imageFile = File(externalImagePath);
    await imageFile.writeAsBytes(imageData);
    bool fileExists = await imageFile.exists();
    if (fileExists) {
      // final bool result =
      //     await WallpaperManager.setWallpaperFromFile(imageFile.path, location);
      // if (result) {
      //   Fluttertoast.showToast(
      //     msg: "Setting successful",
      //     toastLength: Toast.LENGTH_SHORT,
      //     gravity: ToastGravity.TOP,
      //     timeInSecForIosWeb: 1,
      //     backgroundColor: Colors.white,
      //     textColor: Colors.black,
      //     fontSize: 16.0,
      //   );
      // }
    } else {
      Fluttertoast.showToast(
        msg: "La configuración falló, inténtalo de nuevo más tarde.",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.TOP,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  // Future<void> shareAssetImage(String assetName) async {
  //   try {
  //     final bytes = await rootBundle.load(assetName);
  //     final tempDir = await getTemporaryDirectory();
  //     final tempFile = File('${tempDir.path}/shared_image.jpg');
  //     await tempFile.writeAsBytes(bytes.buffer.asUint8List());
  //     await Share.shareXFiles(
  //       [XFile(tempFile.path)],
  //       text: 'Please review the shared images',
  //       sharePositionOrigin: const Rect.fromLTWH(0, 0, 100, 100),
  //       subject: 'Shared Image',
  //       // chooserTitle: 'Share via',
  //     );
  //   } catch (e) {
  //     print('Error sharing asset image: $e');
  //   }
  // }
  Future<void> shareAssetImage(String assetName) async {
    try {

      // 请求网络图片
      final response = await http.get(Uri.parse(imgurl));
      if (response.statusCode == 200) {
        // 获取图片的字节数据
        final Uint8List bytes = response.bodyBytes;
        
        // 获取临时目录
        final Directory tempDir = await getTemporaryDirectory();
        
        // 根据文件扩展名创建临时文件
        String fileExtension = assetName.split('.').last;
        final File tempFile = File('${tempDir.path}/shared_image.$fileExtension');
        
        // 将字节写入文件
        await tempFile.writeAsBytes(bytes.buffer.asUint8List());
        
        // 分享文件
        await Share.shareXFiles(
          [XFile(tempFile.path)],
          text: '¡He compartido una hermosa imagen, espero que te guste!', //我分享了一张美丽的图片，希望你会喜欢！
          sharePositionOrigin: const Rect.fromLTWH(0, 0, 100, 100),
          subject: 'Shared Image',
          // chooserTitle: 'Share via',
        );
        // 这里可以使用 imageBytes 进行后续处理，比如显示图片
        // print('图片字节数据长度: ${imageBytes.length}');
      } else {
        // print('请求失败，状态码: ${response.statusCode}');
      }

      // 加载资源文件
      // final ByteData bytes = await rootBundle.load(assetName);
      
      
    } catch (e) {
      // print('Error sharing asset image: $e');
    }
  }


  Future<bool> requestPermission(BuildContext context) async {
  var status = await Permission.photos.request();
  // print(status.isPermanentlyDenied);
  // print('-----');
  if (status.isGranted) {
    // print('Permission granted');
    return true;
  } else if (status.isDenied) {
    // print('Permission denied');
    // 提示用户权限被拒绝
    showPermissionDeniedDialog(context);
    return false;
  } else if (status.isPermanentlyDenied) {
    // print('Permission permanently denied');
    // 提示用户去设置页面
    showPermissionPermanentlyDeniedDialog(context);
    return false;
  }
  
  return false;
}

void showPermissionDeniedDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('Permiso Denegado'),
        content: const Text('Por favor, permite el acceso a la galería para guardar la imagen.'),
        actions: [
          TextButton(
            child: const Text('OK'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

void showPermissionPermanentlyDeniedDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title:  const Text('Permiso Denegado Permanentemente'),
        content: const Text('Por favor, habilita el acceso a la galería manualmente en la configuración.'),
        actions: [
          TextButton(
            child: const Text('Ir a Configuración'),
            onPressed: () {
              openAppSettings(); // 引导用户到设置页面
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            child: const Text('Cancelar'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}


Future<void> saveGifToGallery(Uint8List bytes, BuildContext context) async {
  bool permissionGranted = await requestPermission(context);
  if (!permissionGranted) {
    // print('Permission not granted, exiting...');
    return; 
  }
  String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
  // 获取临时目录
  var appDocDir = await getTemporaryDirectory();
  String savePath = "${appDocDir.path}/$timestamp.gif"; // 替换为你的文件名

  // 将字节数据写入文件
  File file = File(savePath);
  await file.writeAsBytes(bytes);

  // 保存文件到相册
  final result = await ImageGallerySaver.saveFile(savePath, isReturnPathOfIOS: true);
  // print(result);
  if(result['isSuccess']){
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('¡Guardado con éxito en la galería!', style: TextStyle(fontFamily: 'OpenSans', fontSize: 16),),
        duration: Duration(seconds: 2),
        backgroundColor: Colors.green,
      ),
    );
  }
}

Future<void> saveJpgImage(Uint8List bytes, BuildContext context) async {
  // 获取当前时间戳
  String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
  // 获取临时目录
  var appDocDir = await getTemporaryDirectory();
  String savePath = "${appDocDir.path}/$timestamp.jpg"; // 替换为你的文件名

  // 将字节数据写入文件
  File file = File(savePath);
  await file.writeAsBytes(bytes);

  // 保存文件到相册
  final result = await ImageGallerySaver.saveFile(savePath, isReturnPathOfIOS: true);
  if(result['isSuccess']){
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('¡Guardado con éxito en la galería!', style: TextStyle(fontFamily: 'OpenSans', fontSize: 16),),
        duration: Duration(seconds: 2),
        backgroundColor: Colors.green,
      ),
    );
  }
  // print(result);
}

Future<void> loadAndSaveGif(BuildContext context) async {
  try {

    // 请求网络图片
    final response = await http.get(Uri.parse(imgurl));
    if (response.statusCode == 200) {
      // 获取图片的字节数据
      final Uint8List imageBytes = response.bodyBytes;
      if(gif == 0){
        await saveJpgImage(imageBytes, context);
        
      }else{
        await saveGifToGallery(imageBytes, context);
      }
      // 这里可以使用 imageBytes 进行后续处理，比如显示图片
      // print('图片字节数据长度: ${imageBytes.length}');
    } else {
      // print('请求失败，状态码: ${response.statusCode}');
    }
    
  } catch (e) {
    // print('Error loading or saving GIF: $e');
  }
}

  @override
  Widget build(BuildContext context) {
    var sizewidth = MediaQuery.of(context).size.width;
    
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                offset: const Offset(0, 2),
                blurRadius: 6.0,
              ),
            ],
          ),
          child: AppBar(
            backgroundColor: Colors.white,
            // iconTheme: const IconThemeData(color: Colors.white),
            title: const Text(
              'Tarjeta',
              style:
                   TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
            ),
            leading: IconButton(
              icon: const Icon(CupertinoIcons.back),
              onPressed: () {
                Navigator.of(context).pop();
                _interstitialAd?.show();
                
              },
            ),
          ),
        ),
      ),
      // appBar: AppBar(
      //   backgroundColor: const Color.fromARGB(255, 215, 31, 39),
      //   iconTheme: const IconThemeData(color: Colors.white),
      //   title: const Text(
      //     'Card',
      //     style: TextStyle(fontWeight: FontWeight.bold),
      //   ),
      // ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: sizewidth - 20,
            height: sizewidth - 20,
            child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child:CachedNetworkImage(
                  imageUrl: '$imgurl?x-oss-process=image/resize,p_60',
                  placeholder: (context, url) => const LoadingSpinner(), // 占位图
                  errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                  fit: BoxFit.cover,
                )
              ),
          ),
          const SizedBox(height: 60),
          InkWell(
            // onTap: () async {
            //   try {
                
            //   } catch (e) {
            //     print('Error sharing asset image: $e');
            //   }
            //   // final result = await ImageGallerySaver.saveImage(widget.photourl);
            //   // ScaffoldMessenger.of(context).showSnackBar(
            //   //   const SnackBar(
            //   //     content: Text('Successfully saved to the gallery!', style: TextStyle(fontFamily: 'Ubuntu', fontSize: 16),),
            //   //     duration: Duration(seconds: 2),
            //   //     backgroundColor: Color.fromRGBO(240, 128, 128, 1),
            //   //   ),
            //   // );
            //   // setWallpaperImage(widget.photourl, WallpaperManager.BOTH_SCREEN);
            // },
            onTap: () {
              if(_showWatchVideoButton){
                _rewardedAd?.show(onUserEarnedReward:
                    (AdWithoutView ad, RewardItem rewardItem) {
                   loadAndSaveGif(context);
                  setState(() {
                    _showWatchVideoButton = false;
                  });
                  
                });
              }else{
                loadAndSaveGif(context);
              }
            } , // 替换为你的 GIF 资源路径
            child: Stack(
              children: [
                Container(
                  height: 64,
                  margin: const EdgeInsets.only(left: 32, right: 32, top: 8),
                  decoration: BoxDecoration(
                      color: const Color.fromARGB(255, 215, 31, 39),
                      borderRadius: BorderRadius.circular(32)),
                  child: const Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(CupertinoIcons.cloud_download, color: Colors.white,),
                        SizedBox(width: 6,),
                        Text(
                          'Guardar en la galería',
                          style: TextStyle(
                            color: Colors.white,
                            // fontWeight: FontWeight.w600,
                            fontSize: 20,
                            fontFamily: 'OpenSans',
                          ),
                        )
                      ],
                    ) ,
                  ),
                ),
                Visibility(
                  visible: _showWatchVideoButton,
                  child: Positioned(
                    right: 16,
                    top: 0,
                    child: Container(
                      width: 36,
                      height: 30,
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 252, 229, 13),
                        borderRadius: BorderRadius.circular(15),
                        // image: DecorationImage(
                        //   image: AssetImage('images/ad.png'))
                      ),
                      child: Container(
                        decoration: const BoxDecoration(
                        
                        image: DecorationImage(
                          image: AssetImage('images/ad.png'))
                      ),
                      ),
                    ))
              )
              ],
            ) ,
          ),
          InkWell(
            onTap: () {
              if(_showWatchVideoButton){
                _rewardedAd?.show(onUserEarnedReward:
                    (AdWithoutView ad, RewardItem rewardItem) {
                  shareAssetImage(imgurl);
                  setState(() {
                    _showWatchVideoButton = false;
                  });
                  
                });
              }else{
                shareAssetImage(imgurl);
              }
              
            },
            child: Stack(
              children: [
                Container(
                  height: 64,
                  margin: const EdgeInsets.only(left: 32, right: 32, top: 8),
                  decoration: BoxDecoration(
                      color: const Color.fromARGB(255, 215, 31, 39),
                      borderRadius: BorderRadius.circular(32)),
                  child: const Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(CupertinoIcons.share, color: Colors.white,),
                        SizedBox(width: 6,),
                        Text(
                          'Compartir con amigos',
                          style: TextStyle(
                            color: Colors.white,
                            // fontWeight: FontWeight.w600,
                            fontSize: 20,
                            fontFamily: 'OpenSans',
                          ),
                        )
                      ],
                    ) ,
                  ),
                ),

                Visibility(
                  visible: _showWatchVideoButton,
                  child: Positioned(
                    right: 16,
                    top: 0,
                    child: Container(
                      width: 36,
                      height: 30,
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 252, 229, 13),
                        borderRadius: BorderRadius.circular(15),
                        // image: DecorationImage(
                        //   image: AssetImage('images/ad.png'))
                      ),
                      child: Container(
                        decoration: const BoxDecoration(
                        
                        image: DecorationImage(
                          image: AssetImage('images/ad.png'))
                      ),
                      ),
                    ))
              )
              ],
            ) ,
          )
        ],
      ),
    );
  }

  Future<int> _getAdStatus() async {
    final prefs = await SharedPreferences.getInstance();
    int status = prefs.getInt('insertAdStatus') ?? 1;
    return status;
  }

  /// Loads an interstitial ad.
  void loadInsertAd() async {
    int adStatus = await _getAdStatus();
    if (adStatus != 1) {
      return;
    }
    // Only load an ad if the Mobile Ads SDK has gathered consent aligned with
    // the app's configured messages.
    var canRequestAds = await _consentManager.canRequestAds();
    if (!canRequestAds) {
      return;
    }

    InterstitialAd.load(
        adUnitId: AdsUnitId.insertAdUnitId,
        request: const AdRequest(),
        adLoadCallback: InterstitialAdLoadCallback(
          // Called when an ad is successfully received.
          onAdLoaded: (ad) {
            debugPrint('$ad loaded.');
            // Keep a reference to the ad so you can show it later.
            _interstitialAd = ad;
          },
          // Called when an ad request failed.
          onAdFailedToLoad: (LoadAdError error) {
            debugPrint('InterstitialAd failed to load: $error');
          },
        ));
  }

  void _loadRewardAd() async {
    
    // int adStatus = await _getAdStatus();
    // print('adStatus$adStatus');
    // if (adStatus != 1) {
    //   return;
    // }
    // Only load an ad if the Mobile Ads SDK has gathered consent aligned with
    // the app's configured messages.
    var canRequestAds = await _consentManager.canRequestAds();
    if (!canRequestAds) {
      return;
    }

    RewardedAd.load(
      adUnitId: AdsUnitId.rewardAdUnitId,
      request: const AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(onAdLoaded: (ad) {
        ad.fullScreenContentCallback = FullScreenContentCallback(
            // Called when the ad showed the full screen content.
            onAdShowedFullScreenContent: (ad) {},
            // Called when an impression occurs on the ad.
            onAdImpression: (ad) {},
            // Called when the ad failed to show full screen content.
            onAdFailedToShowFullScreenContent: (ad, err) {
              ad.dispose();
            },
            // Called when the ad dismissed full screen content.
            onAdDismissedFullScreenContent: (ad) {
              ad.dispose();
            },
            // Called when a click is recorded for an ad.
            onAdClicked: (ad) {});

        // Keep a reference to the ad so you can show it later.
        _rewardedAd = ad;

        setState(() {
          _showWatchVideoButton = true;
        });
      }, onAdFailedToLoad: (LoadAdError error) {
        // ignore: avoid_print
        print('RewardedAd failed to load: $error');
      }));
  }
}
